package email

import (
	"crypto/tls"
	"fmt"
	"go-caipu/pkg/tsdb/email/models"
	"strings"

	"gopkg.in/gomail.v2"
)

type GoMailSender struct {
	dialer   *gomail.Dialer
	from     string
	host     string
	port     int
	username string
	password string
	ssl      bool
}

func NewGoMailSender(host string, port int, username, password, from string, ssl bool) *GoMailSender {
	dialer := gomail.NewDialer(host, port, username, password)
	if ssl {
		dialer.SSL = true
		dialer.TLSConfig = &tls.Config{InsecureSkipVerify: true}
	} else {
		dialer.SSL = false
	}

	return &GoMailSender{
		dialer:   dialer,
		from:     from,
		host:     host,
		port:     port,
		username: username,
		password: password,
		ssl:      ssl,
	}
}

// TestDial 测试连接
func (s *GoMailSender) TestDial() error {
	_, err := s.dialer.Dial()
	return err
}
func (s *GoMailSender) Send(email *models.Email) error {
	m := gomail.NewMessage()

	// 设置发件人
	m.SetHeader("From", s.from)

	// 设置收件人
	to := strings.Split(email.To, ",")
	m.SetHeader("To", to...)

	// 设置抄送
	if email.Cc != "" {
		cc := strings.Split(email.Cc, ",")
		m.SetHeader("Cc", cc...)
	}

	// 设置密送
	if email.Bcc != "" {
		bcc := strings.Split(email.Bcc, ",")
		m.SetHeader("Bcc", bcc...)
	}

	// 设置主题
	m.SetHeader("Subject", email.Subject)

	// 设置邮件正文
	if email.ContentType == "text/html" {
		m.SetBody("text/html", email.Body)
	} else {
		m.SetBody("text/plain", email.Body)
	}

	// 设置Message-ID
	if email.MessageID != "" {
		m.SetHeader("Message-ID", email.MessageID)
	}

	// 发送邮件
	if err := s.dialer.DialAndSend(m); err != nil {
		return fmt.Errorf("failed to send email: %w", err)
	}

	return nil
}
